package summary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/16 9:04
 * https://leetcode-cn.com/problems/permutations/
 */
public class Title46 {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> list = new LinkedList<>();
    boolean[] flag;
    public List<List<Integer>> permute(int[] nums) {
        flag = new boolean[nums.length];
        backTracking(nums);
        return result;
    }

    private void backTracking(int[] nums) {
        if (list.size() == nums.length) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!flag[i]) {
                list.offer(nums[i]);
                flag[i] = true;
            } else {
                continue;
            }
            backTracking(nums);
            list.removeLast();
            flag[i] = false;
        }
    }



    public List<List<Integer>> permute2(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> temp = new LinkedList<>();
        boolean[] flag = new boolean[nums.length];
        backTracking1(result, temp, nums, flag);

        return result;
    }

    private void backTracking1(List<List<Integer>> result, LinkedList<Integer> temp, int[] nums, boolean[] flag) {
        if (temp.size() == nums.length) {
            result.add(new ArrayList<>(temp));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (flag[i]) {
                continue;
            }
            temp.offer(nums[i]);
            flag[i] = true;
            backTracking1(result, temp, nums, flag);
            temp.removeLast();
            flag[i] = true;
        }
    }

    public static void main(String[] args) {

    }
}
